import DrawerFooter from '@/components/DrawerFooter';
import InputSelect from '@/components/InputSelect';
import { Button, Dialog, Field, Form, Loading, Message, NumberPicker, ResponsiveGrid, Step } from '@alifd/next';
import { t } from '@lingui/macro';
import dayjs from 'dayjs';
import { observable } from 'mobx';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { getBcInfo, userForMobile, usersForMobile } from '../stores/api';
import { FieldsGrid, TitleGrid } from '../stores/definitions';

const FromItem = Form.Item;
const { Cell } = ResponsiveGrid;

const defaultOrder = {
  busOrder: {
    currencyId: 'RMB',
    shift: {
      date: dayjs(),
    },
  },
  price: 0.0,
};

function AddForm({ onCancel, onSubmit, modal }) {
  const [order] = useState(() => observable(_.cloneDeep(defaultOrder)));
  const [step, setStep] = useState(0);
  const formField = Field.useField();
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改

  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  // 当前Form中，重载模型定义
  const overrideModel = useMemo(() => ({
    busOrder: {
      phone: {
        ui: {
          renderer: () => <InputSelect onFetch={usersForMobile} labelField="fullname" valueField="mobile" />,
        },
      },
      fullname: {
        ui: { itemProps: { disabled: true } },
      },
      collectorName: {
        ui: { span: 3 },
      },
      collectorPhone: {
        ui: { span: 3 },
      },
    },
    price: {
      label: t`订单总价`,
      ui: {
        renderer: (v) => <span style={{ color: 'red', fontWeight: 500, fontSize: 'larger' }}>{currencySign(order.busOrder.currencyId)}{v?.toFixed(2)}元</span>,
        span: 3,
      },
    },
  }), []);

  const handleChange = (values, item) => {
    const { name, value, field } = item;
    _.set(order, name, value);
    // 联动效果可以在这里通过设置order属性实现
    if (name === 'busOrder.phone') {
      field.validate(['busOrder.phone']);
      const err = field.getError('busOrder.phone');
      // console.log('err', err);
      if (!err?.length) {
        // 联动远程获取数据
        (async () => {
          const res = await userForMobile(value);
          // console.log('res', res);
          _.set(order, 'busOrder.fullname', res.fullname);
          field.reset(['busOrder.fullname']);
        })();
      }
    }
    if (name === 'busOrder.from.city') {
      _.unset(order, 'busOrder.to'); // 设置出发城市时清空到达城市
      _.unset(order, 'busOrder.from.station');
      _.unset(order, 'busOrder.shift.scheduleId');
      _.unset(order, 'busOrder.returnFrom');
      _.unset(order, 'busOrder.returnTo');
      _.unset(order, 'busOrder.returnShift.scheduleId');
    }
    if (name === 'busOrder.to.city') {
      _.unset(order, 'busOrder.to.station');
      _.unset(order, 'busOrder.shift.scheduleId');
      _.unset(order, 'busOrder.returnFrom');
      _.unset(order, 'busOrder.returnTo');
      _.unset(order, 'busOrder.returnShift.scheduleId');
    }
    if (name === 'busOrder.isRoundTrip') {
      if (value === true) {
        _.set(order, 'busOrder.returnFrom.city', order.busOrder.to?.city);
        _.set(order, 'busOrder.returnTo.city', order.busOrder.from?.city);
        _.set(order, 'busOrder.returnShift.date', order.busOrder.shift?.date);
        _.set(order, 'busOrder.returnFrom.station', order.busOrder.to?.station);
        _.set(order, 'busOrder.returnTo.station', order.busOrder.from?.station);
      } else {
        _.unset(order, 'busOrder.returnFrom');
        _.unset(order, 'busOrder.returnTo');
        _.unset(order, 'busOrder.returnShift');
        field.reset(['busOrder.returnFrom.station', 'busOrder.returnTo.station', 'busOrder.returnShift.date', 'busOrder.returnShift.scheduleId']);
      }
    }

    if (name === 'busOrder.from.station' || name === 'busOrder.to.station' || name === 'busOrder.shift.date') {
      _.unset(order, 'busOrder.shift.scheduleId');
    }
    if (name === 'busOrder.returnFrom.station' || name === 'busOrder.returnTo.station' || name === 'busOrder.returnShift.date') {
      _.unset(order, 'busOrder.returnShift.scheduleId');
    }

    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign, no-param-reassign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleNext = (value, errors, _field) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: AddForm.jsx:133 _ errors:', errors);
      return;
    }
    if (step === 1) {
      // FIXME 提交数据
      if (!order.busOrder.orderDetails?.length) {
        Message.error(t`请添加至少1张车票`);
        return;
      }
    }
    if (step === 2) {
      _.update(order, 'busOrder.shift.date', (v) => v?.toJSON());
      _.update(order, 'busOrder.returnShift.date', (v) => v?.toJSON());
      onSubmit?.(toJS(order));
      return;
    }
    setStep(step + 1);
  };

  const handlePrior = () => {
    // if (step === 1) {
    //   formField.reset(['busOrder.price']);
    // }
    setStep(step - 1);
  };

  return (
    <Form
      field={formField}
      inline
      useLabelForErrorMessage
      value={order}
      onChange={handleChange}
      onSubmit={handleNext}
    >
      <Step current={step} stretch shape="circle" style={{ width: '50%', marginLeft: '25%' }}>
        <Step.Item title={t`基本信息`} />
        <Step.Item title={t`车票信息`} />
        <Step.Item title={t`订单确认`} />
      </Step>
      {step === 0 && <StepBasic order={order} overrideModel={overrideModel} />}
      {step === 1 && <StepTicket order={order} overrideModel={overrideModel} />}
      {step === 2 && <StepConfirm order={order} overrideModel={overrideModel} />}
      <DrawerFooter>
        <FromItem>
          <Button style={{ marginRight: 8 }} onClick={handleCancel}>{t`取消`}</Button>
          {step > 0 && <Button style={{ marginRight: 8 }} onClick={handlePrior}>{t`上一步`}</Button>}
          <Form.Submit validate type="primary" onClick={handleNext}>{step < 2 ? t`下一步` : t`提交订单`}</Form.Submit>
        </FromItem>
      </DrawerFooter>
    </Form>
  );
}

const StepBasic = ({ order, overrideModel, mode = 'edit' }) => {
  const { isRoundTrip } = order.busOrder;
  return (
    <div style={{ padding: 20 }}>
      <FieldsGrid
        formData={order}
        mode={mode}
        overrideModel={overrideModel}
        fields={['busOrder.phone', 'busOrder.fullname', 'busOrder.partnerId', 'busOrder.currencyId',
          'busOrder.from.city', 'busOrder.to.city', 'busOrder.isRoundTrip']}
      />
      {isRoundTrip && <TitleGrid title={t`去程`} />}
      <FieldsGrid
        formData={order}
        mode={mode}
        overrideModel={overrideModel}
        fields={['from.station', 'to.station', 'shift.date', 'shift.scheduleId'].map((s) => `busOrder.${s}`)}
      />
      {isRoundTrip && <TitleGrid title={t`回程`} />}
      {isRoundTrip && <FieldsGrid
        formData={order}
        mode={mode}
        overrideModel={overrideModel}
        fields={['returnFrom.station', 'returnTo.station', 'returnShift.date', 'returnShift.scheduleId'].map((s) => `busOrder.${s}`)}
      />}
    </div >
  );
};

const StepTicket = ({ order, overrideModel, mode = 'edit' }) => {
  const [prices, setPrices] = useState([]);
  const tickets = useRef({}).current;
  const [loading, setLoading] = useState(true);
  const isViewMode = mode === 'view';
  useEffect(() => {
    (async () => {
      try {
        const res = await getBcInfo({
          runId: order.busOrder.shift.scheduleId,
          currencyId: order.busOrder?.currencyId,
          originId: order.busOrder?.from?.station,
          destinationId: order.busOrder?.to?.station,
          isReturn: order.busOrder?.isRoundTrip ? 1 : 0,
          priceType: '',
        });
        setPrices(res.prices);
        _.set(order, 'busOrder.prices', res.prices);
      } finally {
        setLoading(false);
      }
    })();
  }, []);

  const handleTicketCount = (price, count) => {
    tickets[price.ticketCategoryId] = Array(count).fill().map((_) => ({
      passenger: 'ZAKC',
      passengerTel: '12345678900',
      busTicketType: price.ticketTypeId,
      ticketCategoryLineId: price.ticketCategoryId,
      passengerEmail: '',
      passengerFlightNo: '',
      ticketPrice: Number(price.fee),
    }));
    const flat = _.values(tickets).flat();
    _.set(order, 'busOrder.orderDetails', flat.map((t0) => { const tmp = { ...t0 }; delete tmp.ticketPrice; return tmp; }));
    const totalPrice = flat.reduce((sum, t1) => sum + t1.ticketPrice, 0);
    _.set(order, 'price', totalPrice);
  };

  function getCount(price) {
    return order.busOrder.orderDetails?.filter((tp) => tp.ticketCategoryLineId === price.ticketCategoryId).length;
  }

  return (
    <div style={{ padding: '20px 100px' }}>
      <FieldsGrid
        columns={12}
        formData={order}
        mode={mode}
        overrideModel={overrideModel}
        fields={['', '', 'busOrder.collectorName', 'busOrder.collectorPhone', 'price']}
      />
      <ResponsiveGrid columns={12} gap={[6, 24]} style={{ marginTop: 20, marginBottom: 8, fontWeight: 500 }}>
        <Cell colSpan={2} />
        <Cell colSpan={3}>{t`票种`}</Cell>
        <Cell colSpan={2} {..._.merge({ style: { textAlign: 'right' } })}>{t`单价`}</Cell>
        <Cell colSpan={5} {..._.merge({ style: { paddingLeft1: 24 } })}>{t`乘客数`}</Cell>
      </ResponsiveGrid>
      {/* <Loading style={{ height: 100, width: '100%' }} /> */}
      {loading ?
        <Loading style={{ height: 100, width: '100%' }} /> :
        <ResponsiveGrid columns={12} gap={[6, 24]} style={{ marginBottom: 10 }} >
          {prices.map((p) => (
            <React.Fragment key={p.ticketCategoryId}>
              <Cell colSpan={2} />
              <Cell colSpan={3}>{p.ticketType}</Cell>
              <Cell colSpan={2} style={{ textAlign: 'right', color: 'red', fontWeight: 500 }}>{currencySign(order.busOrder.currencyId)}{p.fee}</Cell>
              <Cell colSpan={5}>{isViewMode ? getCount(p) : <NumberPicker defaultValue={0} type="inline" onChange={(c) => handleTicketCount(p, c)} />}</Cell>
            </React.Fragment>
          ))}
        </ResponsiveGrid>}
    </div>
  );
};

const StepConfirm = ({ order, overrideModel }) => {
  return (
    <div style={{ padding: 20 }}>
      <StepBasic mode="view" order={order} overrideModel={overrideModel} />
      <StepTicket mode="view" order={order} overrideModel={overrideModel} />
    </div>
  );
};


export default observer(AddForm);


/*
{
    "from": {
        "city": "001",
        "station": "352",
        "stationName": "深圳寶安國際機場",
        "onAddress": "宝安区福永镇深圳机场T3航站楼地面交通中心(GTC)11号门斜对面问询柜台旁，服务柜台",
        "offAddress": "宝安区福永镇深圳机场T3航站楼"
    },
    "to": {
        "city": "002",
        "station": "371",
        "stationName": "上環信德中心",
        "onAddress": "上環信德中心地下G04-05鋪位(港鐵上環站D出口)",
        "offAddress": "中港道信德中心地下(港鐵上環站D出口) "
    },
    "returnFrom": {
        "city": "001",
        "station": "",
        "stationName": "",
        "onAddress": "",
        "offAddress": ""
    },
    "returnTo": {
        "city": "",
        "station": "",
        "stationName": "",
        "onAddress": "",
        "offAddress": ""
    },
    "isOpen": false,
    "returnIsOpen": false,
    "currencyId": "RMB",
    "isRoundTrip": false,
    "collectorName": "取票人",
    "collectorPhone": "18888888",
    "partnerId": "",
    "fullname": "zhang",
    "username": "13530380987@mzd",
    "phone": "13530380987",
    "shift": {
        "date": "2023-09-12T17:00:00.000Z",
        "companyId": "zgt",
        "companyName": "中港通",
        "scheduleId": "7569238"
    },
    "returnShift": {
        "date": "",
        "companyId": "",
        "companyName": "",
        "scheduleId": ""
    },
    "prices": [
        {
            "fee": "20",
            "isReturn": "0",
            "lawTicketType": "1",
            "priceId": "1390563",
            "stdPrivFlg": "1",
            "ticketCategoryId": "101390563",
            "ticketCategoryName": "",
            "ticketType": "嬰兒0-3歲",
            "ticketTypeId": "3",
            "ticketCategoryLineId": "",
            "num": 2
        },
        {
            "fee": "130",
            "isReturn": "0",
            "lawTicketType": "1",
            "priceId": "1390497",
            "stdPrivFlg": "1",
            "ticketCategoryId": "101390497",
            "ticketCategoryName": "",
            "ticketType": "成人",
            "ticketTypeId": "9",
            "ticketCategoryLineId": "",
            "num": 3
        }
    ],
    "priceType": "",
    "orderDetails": [
        {
            "passenger": "ZAKC",
            "passengerTel": "12345678900",
            "busTicketType": "3",
            "ticketCategoryLineId": "101390563",
            "passengerEmail": "",
            "passengerFlightNo": ""
        },
        {
            "passenger": "ZAKC",
            "passengerTel": "12345678900",
            "busTicketType": "3",
            "ticketCategoryLineId": "101390563",
            "passengerEmail": "",
            "passengerFlightNo": ""
        },
        {
            "passenger": "ZAKC",
            "passengerTel": "12345678900",
            "busTicketType": "9",
            "ticketCategoryLineId": "101390497",
            "passengerEmail": "",
            "passengerFlightNo": ""
        },
        {
            "passenger": "ZAKC",
            "passengerTel": "12345678900",
            "busTicketType": "9",
            "ticketCategoryLineId": "101390497",
            "passengerEmail": "",
            "passengerFlightNo": ""
        },
        {
            "passenger": "ZAKC",
            "passengerTel": "12345678900",
            "busTicketType": "9",
            "ticketCategoryLineId": "101390497",
            "passengerEmail": "",
            "passengerFlightNo": ""
        }
    ]
}
*/
